# 简化的Java 21安装脚本
Write-Host "开始安装 Java 21 LTS..." -ForegroundColor Green

# 下载Java 21
$downloadUrl = "https://download.java.net/java/GA/jdk21.0.2/f2283984656d49d69e91c558476027ac/13/GPL/openjdk-21.0.2_windows-x64_bin.zip"
$zipPath = "$env:TEMP\openjdk-21.zip"
$installDir = "C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot"

Write-Host "下载 Java 21..." -ForegroundColor Yellow
try {
    Invoke-WebRequest -Uri $downloadUrl -OutFile $zipPath -UseBasicParsing
    Write-Host "下载完成" -ForegroundColor Green
} catch {
    Write-Host "下载失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请手动下载 Java 21 从: https://adoptium.net/temurin/releases/?version=21" -ForegroundColor Yellow
    exit 1
}

# 创建安装目录
Write-Host "创建安装目录..." -ForegroundColor Yellow
if (!(Test-Path $installDir)) {
    New-Item -ItemType Directory -Path $installDir -Force
}

# 解压
Write-Host "解压 Java 21..." -ForegroundColor Yellow
try {
    Expand-Archive -Path $zipPath -DestinationPath "C:\Program Files\Eclipse Adoptium\" -Force
    
    # 查找解压后的文件夹并重命名
    $extractedFolder = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" | Where-Object { $_.Name -like "jdk-21*" -and $_.Name -notlike "*hotspot" } | Select-Object -First 1
    if ($extractedFolder) {
        if (Test-Path $installDir) {
            Remove-Item $installDir -Recurse -Force
        }
        Rename-Item $extractedFolder.FullName $installDir -Force
    }
    
    Write-Host "Java 21 安装完成" -ForegroundColor Green
} catch {
    Write-Host "解压失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 设置环境变量
Write-Host "设置环境变量..." -ForegroundColor Yellow
[Environment]::SetEnvironmentVariable("JAVA_HOME", $installDir, "User")

# 更新PATH
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
$javaBin = "$installDir\bin"
$pathArray = $currentPath -split ";" | Where-Object { $_ -notlike "*jdk*\bin" -and $_ -notlike "*java*\bin" }
$newPath = ($javaBin, $pathArray) -join ";"
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")

# 刷新当前会话
$env:JAVA_HOME = $installDir
$env:Path = "$javaBin;$env:Path"

Write-Host "环境变量设置完成" -ForegroundColor Green
Write-Host "JAVA_HOME: $installDir" -ForegroundColor Cyan

# 验证安装
Write-Host "验证安装..." -ForegroundColor Yellow
try {
    & "$javaBin\java.exe" -version
    Write-Host "Java 21 安装成功！" -ForegroundColor Green
} catch {
    Write-Host "验证失败，请重新启动 PowerShell" -ForegroundColor Yellow
}

# 清理
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue

Write-Host "安装完成！请重新启动 PowerShell 或 IDE" -ForegroundColor Green